import React, { useState } from "react";
import { Button, Modal } from "antd";
import { MessageItem } from "./types";
import { HumanInputMessage } from "./stoppedOperations";
import FlightSelectionModal from "./FlightSelectionModal";
import { FlightOption } from "../../services/apiService";
import { useTranslation } from 'react-i18next';

interface HumanInputModalProps {
  humanInputModal: {
    humanInputMessage: HumanInputMessage | null;
    visible: boolean;
    nodeId: string;
    nodeLabel: string;
    nodeData?: any; // 可选的节点数据，包含按钮配置等
  };
  loading: boolean;
  onDecision: (decision: "proceed" | "reject" | "cancel", data?: {}, msgInfo?: string) => void;
}

const HumanInputModal: React.FC<HumanInputModalProps> = ({
  humanInputModal,
  loading,
  onDecision,
}) => {
  const { t } = useTranslation();
  const { visible, nodeId, nodeLabel, nodeData, humanInputMessage } =
    humanInputModal;
  if (!humanInputMessage) {
    return null; // 如果没有 humanInputMessage，则不渲染 Modal
  }

  // 基于 nodeLabel 的自定义按钮标签映射
  const getCustomButtonLabels = (nodeLabel: string) => {
    switch (nodeLabel) {
      case "Q-人工操作-是否需要攻略":
        return {
          proceed: t('humanInputModal.useGuide'),
          reject: t('humanInputModal.generateGuide'),
        };
      case "人工操作-航班自选":
        return {
          proceed: t('humanInputModal.selectFlight'),
          reject: t('humanInputModal.useDefaultFlight'),
        };
      default:
        // 返回 null 表示使用后端或默认标签
        return {
          proceed: t('humanInputModal.agree'),
          reject: t('humanInputModal.reject'),
        };
    }
  };

  const finalLabels = getCustomButtonLabels(nodeLabel);

  if (nodeLabel === "人工操作-航班自选") {
    return (
      <FlightSelectionModal
        visible={visible}
        onReject={(nodeId) => onDecision("reject",{}, finalLabels.reject)}
        loading={loading}
        nodeId={nodeId}
        nodeLabel={nodeLabel}
        nodeData={humanInputMessage.AIQuestion}
        onProceed={(flightInfo, nodeId, selectedFlight, flightList: FlightOption[]) =>
          onDecision("proceed", { flightInfo, selectedFlight, flightList }, finalLabels.proceed)}
        onCancel={() => onDecision("cancel")}
      />
    )
  } else {
    return (
      <Modal
        title={t('humanInputModal.confirmTitle')}
        open={visible}
        onCancel={() => onDecision("cancel")}
        footer={[
          <Button
            key="proceed"
            type="primary"
            onClick={() => onDecision("proceed", {}, finalLabels.proceed)}
            disabled={loading}
          >
            {finalLabels.proceed}
          </Button>,
          <Button
            key="reject"
            onClick={() => onDecision("reject", {}, finalLabels.reject)}
            disabled={loading}
          >
            {finalLabels.reject}
          </Button>,
          <Button key="cancel" type="link" onClick={() => onDecision("cancel")}>
            {t('humanInputModal.cancelOperation')}
          </Button>,
        ]}
        closable={false}
        maskClosable={false}
        width={400}
      >
        <div style={{ padding: "16px 0" }}>
          <p>
            {(() => {
              const content = humanInputMessage.AIQuestion;
              // 提取 reason 字段
              const reasonMatch = content.match(/"reason"\s*:\s*"([^"]*)"/);
              // 提取最后一段文本（假设为最后一个换行后的内容，或全部内容）
              const lastParagraphMatch = content.match(/(?:\n|^)([^\n]+)\s*$/);
              return (
                <>
                  {reasonMatch && (
                    <div>
                      <strong>{t('humanInputModal.aiAnalysis')}:</strong> {reasonMatch[1]}
                    </div>
                  )}
                  {lastParagraphMatch && (
                    <div>
                      <strong> {lastParagraphMatch[1]}</strong>
                    </div>
                  )}
                </>
              );
            })()}
          </p>
          <p>{t('humanInputModal.confirmMessage')}</p>
        </div>
      </Modal>
    );
  };
}

export default HumanInputModal;
